<?php

use Throwable;
use Monolog\Handler\StreamHandler;

class Server
{
    protected $ip;

    protected $port;

    protected $socket;

    protected $reactor;

    public function __construct($ip, $port)
    {
        $this->ip = $ip;
        $this->port = $port;
    }

    public function start()
    {
        $socket = $this->createTcpConnection();
        stream_set_blocking($socket, false); //是否阻塞

        Reactor::getInstance()->add($socket, Reactor::READ, function($socket) {
            $conn = stream_socket_accept($socket);
            stream_set_blocking($conn, false);
            (new Connection($conn))->handle();
        });

        Reactor::getInstance()->run();
    }

    public function createTcpConnection()
    {
        $schema = sprintf("tcp://%s:%d", $this->ip, $this->port);
        $socket = stream_socket_server($schema, $errno, $errstr);

        if ($errno) {
            throw new \Exception($errstr);
        }

        return $socket;
    }
}